package com.dcsec.server.printer;


import cn.hutool.core.util.StrUtil;
import com.dcsec.server.bean.PrintParam;
import com.dcsec.server.util.ImageToZplUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.print.*;
import javax.print.attribute.standard.PrinterName;
import java.io.IOException;
import java.util.List;


public class ZplPrinter {

    private static final Logger log = LoggerFactory.getLogger(ZplPrinter.class);

    // 打印机名称
    private static String printName = "ZDesigner ZT411R-600dpi ZPL";

    // 打印机服务
    private static PrintService printService = null;

    public static void main(String[] args) {

        try {

            String imageUrl = "C:\\thy\\develop\\javacode\\evidence-server\\out\\artifacts\\evidence_server_war_exploded\\export\\1721117310890.png";

            ZplPrinter.print("epc","userData",imageUrl,null);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("打印失败：未找到打印机");
        }
    }

    /**
     * 连接打印机
     *
     * @param printName 打印机路径
     */
    private static void connect(String printName) {

        if (!StrUtil.isEmpty(printName)) {
            ZplPrinter.printName = printName;
        }

        // 初始化打印机
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
        if (services != null && services.length > 0) {
            for (PrintService service : services) {

                log.debug(service.getName());
                System.err.println(service.getName());

                if (ZplPrinter.printName.equals(service.getName())) {
                    printService = service;
                    break;
                }
            }
        }

        if (printService == null) {
            log.error("打印失败：未找到打印机");
            throw new RuntimeException("打印失败：未找到打印机");
        } else {
            System.out.println("找到打印机：[" + ZplPrinter.printName + "]");
            System.out.println("打印机名称：[" + printService.getAttribute(PrinterName.class).getValue() + "]");
        }
    }

    /**
     * 打印
     * @param epc
     * @param userData 用户区数据
     * @param imageUrl 图片地址
     */
    public static void print(String epc, String userData, String imageUrl) {
        print(epc, userData, imageUrl,null);
    }

    /**
     * 打印
     * @param epc
     * @param userData 用户区数据
     * @param imageUrl 图片地址
     */
    public static void print(String epc, String userData, String imageUrl, String printName) {

        if (printService==null) {
            connect(printName);
        }

        String imageZpl = ImageToZplUtil.convertFromImg(imageUrl);

        StringBuffer zpl = new StringBuffer();
        zpl.append("^XA");
        zpl.append(imageZpl);
        zpl.append("^RFW,H,2,1,E^FD" + epc + "^FS");
        zpl.append("^RFW,H,0,64,3^FD" + userData + "^FS");
        zpl.append("^XZ");

        try {
            if (printService == null) {
                log.error("打印失败：未找到打印机");
                throw new RuntimeException("打印失败：未找到打印机");
            }

            DocPrintJob job = printService.createPrintJob();
            byte[] by = zpl.toString().getBytes();
            DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
            Doc doc = new SimpleDoc(by, flavor, null);

            job.print(doc, null);
        } catch (PrintException e) {
            log.error("打印失败：打印机无法打印："+e.getMessage());
            throw new RuntimeException("打印失败：打印机无法打印");
        }
    }

    /**
     * 打印
     * @param printParams 打印参数集合
     */
    public static void printToParams(String printerName, List<PrintParam> printParams) {

        if (printParams.isEmpty()) {
            log.error("打印失败：打印信息为空");
            throw new RuntimeException("打印失败：打印信息为空");
        }

        for (PrintParam data : printParams){
            print(data.getEpc(),data.getUserData(),data.getImageUrl(), printerName);
        }
    }
}